const crypto = require('crypto');
const resBody = {
    notLoggedIn: {
        code: 401,
        msg: '登录失效'
    },
    success: {
        code: 0,
        msg: 'success'
    },
    permissionError: {
        code: -1,
        msg: '没有权限'
    },
    paramError: {
        code: -1,
        msg: '参数错误'
    },
    responseError: {
        code: -1,
        msg: '响应错误'
    },
    updateFail: {
        code: -1,
        msg: '更新数据失败'
    },
    createFail: {
        code: -1,
        msg: '创建失败'
    },
    emptyArray: {
        code: -1,
        msg: '列表为空'
    },
    undefined: {
        code: -1,
        msg: '未知错误'
    },
    failed: {
        code: -1,
        msg: '操作失败'
    },
    userNotVerified: {
        code: -2,
        msg: '用户不存在'
    },
    userNotLogin: {
        code: -10,
        msg: '请先登陆后操作'
    },
    verifyCodeErr: {
        code: -3,
        msg: '验证码错误'
    },
    passWordErr: {
        code: -4,
        msg: '密码错误'
    }
};
const dateFormat = (date, fmt = 'yyyy-MM-dd') => {
    if (!date) {
        date = new Date();
    }
    if (typeof time === 'string' ||
        typeof time === 'number') {
        date = new Date(date);
    }
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "H+": date.getHours(), //小时
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
const genTimeStamp = () => {
    return new Date().getTime();
};

function rangeRadom(max, min) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomArray(Min, Max, ArrLen) {
    ArrLen ? ArrLen = ArrLen : ArrLen = 1000;
    let array = [];
    while (array.length <= ArrLen) {
        let randomData = rangeRadom(Min, Max);
        if (!array.includes(randomData)) {
            array.push(randomData);
        }
    }
    return array;
};
const md5 = (str) => {
    return crypto.createHash('md5').update(String(str), 'utf-8').digest('hex');
};

module.exports = {
    mobileReg: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
    emailReg: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
    dateFormat,
    genTimeStamp,
    resBody,
    rangeRadom,
    randomArray,
    md5,
}